﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.ETL
{
    /// <summary>
    /// 
    /// </summary>
    public partial class DownloadTablesEditor : Form, IComponentEditor
    {
        private object _ActivityNode;
        private DownloadTablesComponent _Downloader;

        /// <summary>
        /// 
        /// </summary>
        public DownloadTablesEditor()
        {
            InitializeComponent();
        }

        private void DownloadTablesEditor_Load(object sender, EventArgs e)
        {
            this.cbo_TgtFormats.Items.Clear();
            foreach(FileFormat format in Enum.GetValues(typeof(FileFormat)))
            {
                this.cbo_TgtFormats.Items.Add(format.ToString());
            }
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_ConnStr.Text) && 
                !string.IsNullOrEmpty(this.txt_Schema.Text))
            {
                this.clb_Tables.Items.Clear();
                string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL, this.txt_Schema.Text,
                                                         this.txt_ConnStr.Text);
                if(tblNames !=null && tblNames.Length>0)
                {
                    foreach(string tblName in tblNames)
                    {
                        this.clb_Tables.Items.Add(tblName);
                    }
                }
            }
        }

        private void btn_Browse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg=new FolderBrowserDialog();
            if(dlg.ShowDialog()==DialogResult.OK)
            {
                this.txt_TgtFolder.Text = dlg.SelectedPath;
            }
        }

        #region Implementation of IComponentEditor

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        /// <summary></summary>
        public object OwnerActivityNode
        {
            get { return _ActivityNode; }
            set { _ActivityNode=value; }
        }

        /// <summary></summary>
        public Type WorkflowComponentType
        {
            get { return typeof(DownloadTablesComponent); }
        }

        /// <summary></summary>
        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents, object activityNode, WorkflowComponentBase wfComponent)
        {
            this._ActivityNode = activityNode;
            this._Downloader = (DownloadTablesComponent) wfComponent;

            DownloadTablesInstruction instruction = (DownloadTablesInstruction) this._Downloader.Instruction;
            this.txt_ConnStr.Text = instruction.ConnStr;
            this.lb_SchemaTables.Items.Clear();
            if(instruction.TablesBySchema !=null && instruction.TablesBySchema.Count>0)
            {
                foreach(string schema in instruction.TablesBySchema.Keys)
                {
                    foreach(string tbl in instruction.TablesBySchema[schema])
                    {
                        this.lb_SchemaTables.Items.Add(schema + "." + tbl);
                    }
                }
            }
            this.txt_TgtFolder.Text = instruction.TargetFolderPath;
            for(int i=0;i<this.cbo_TgtFormats.Items.Count;i++)
            {
                if(this.cbo_TgtFormats.Items[i].ToString()==instruction.TgtFileFormat.ToString())
                {
                    this.cbo_TgtFormats.SelectedIndex = i;
                    break;
                }
            }
            this.dv_SqlTbls.Rows.Clear();
            if (instruction.TablesBySql != null && instruction.TablesBySql.Count > 0)
            {
                foreach (string tblName in instruction.TablesBySql.Keys)
                {
                    DataGridViewRow dr = new DataGridViewRow();
                    DataGridViewTextBoxCell cellTblName = new DataGridViewTextBoxCell();
                    cellTblName.Value = tblName;
                    dr.Cells.Add(cellTblName);
                    DataGridViewTextBoxCell cellSql = new DataGridViewTextBoxCell();
                    cellSql.Value = instruction.TablesBySql[tblName];
                    dr.Cells.Add(cellSql);
                    this.dv_SqlTbls.Rows.Add(dr);
                }
            }
        }

        /// <summary></summary>
        public void SaveSettings()
        {
            DownloadTablesInstruction instruction = (DownloadTablesInstruction) this._Downloader.Instruction;
            instruction.ConnStr = this.txt_ConnStr.Text;
            instruction.TablesBySchema=new Dictionary<string, List<string>>();
            for(int i=0;i<this.lb_SchemaTables.Items.Count;i++)
            {
                string[] pair = this.lb_SchemaTables.Items[i].ToString().Split(new char[] {'.'});
                if(instruction.TablesBySchema.ContainsKey(pair[0]))
                {
                    List<string> tblNames = instruction.TablesBySchema[pair[0]];
                    tblNames.Add(pair[1]);
                    instruction.TablesBySchema[pair[0]] = tblNames;
                }
                else
                {
                    List<string> tblNames=new List<string>();
                    tblNames.Add(pair[1]);
                    instruction.TablesBySchema.Add(pair[0],tblNames);
                }
            }
            instruction.TablesBySql = new Dictionary<string, string>();
            foreach (DataGridViewRow dr in this.dv_SqlTbls.Rows)
            {
                if (!dr.IsNewRow && dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                {
                    string tblName = dr.Cells[0].Value.ToString();
                    string sql = dr.Cells[1].Value.ToString();
                    instruction.TablesBySql.Add(tblName, sql);
                }
            }

            instruction.TargetFolderPath = this.txt_TgtFolder.Text;
            if (this.cbo_TgtFormats.SelectedIndex >= 0)
            {
                instruction.TgtFileFormat = (FileFormat) Enum.Parse(
                                                             typeof (FileFormat),
                                                             this.cbo_TgtFormats.Text);
            }
            else
                instruction.TgtFileFormat = FileFormat.ExcelFile;
        }

        /// <summary></summary>
        public TestResult Test()
        {
            throw new System.NotImplementedException();
        }

        #endregion

        private void btn_AddTables_Click(object sender, EventArgs e)
        {
            for(int i=0;i<this.clb_Tables.Items.Count;i++)
            {
                if(this.clb_Tables.GetItemChecked(i))
                {
                    this.lb_SchemaTables.Items.Add(string.Format("{0}.{1}", this.txt_Schema.Text,
                                                                 this.clb_Tables.Items[i]));
                }
            }
        }

        private void btn_RemoveTables_Click(object sender, EventArgs e)
        {
            List<string> schemaTbls=new List<string>();
            for(int i=0;i<this.lb_SchemaTables.Items.Count;i++)
            {
                if(this.lb_SchemaTables.SelectedIndices==null || 
                    !this.lb_SchemaTables.SelectedIndices.Contains(i))
                {
                    schemaTbls.Add(this.lb_SchemaTables.Items[i].ToString());
                }
            }
            this.lb_SchemaTables.Items.Clear();
            if(schemaTbls.Count>0)
            {
                foreach(string name in schemaTbls)
                {
                    this.lb_SchemaTables.Items.Add(name);
                }
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if (this.UpdateComponentSettingEvent != null)
                this.UpdateComponentSettingEvent(this._ActivityNode, this._Downloader);
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_AddSqlTbl_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txt_SqlTblName.Text) &&
                !string.IsNullOrEmpty(this.rt_SQL.Text))
            {
                DataGridViewRow dr = new DataGridViewRow();
                DataGridViewTextBoxCell cellTblName = new DataGridViewTextBoxCell();
                cellTblName.Value = this.txt_SqlTblName.Text;
                dr.Cells.Add(cellTblName);
                DataGridViewTextBoxCell cellSql = new DataGridViewTextBoxCell();
                cellSql.Value = this.rt_SQL.Text;
                dr.Cells.Add(cellSql);
                this.dv_SqlTbls.Rows.Add(dr);
            }
        }
    }
}
